package com.log4jviewer.ui.preferences.additional;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Text;

/**
 * Editor for the column with width preferences.
 * 
 * @author <a href="mailto:rd.ryly@gmail.com">Ruslan Diachenko</a>
 */
public class ColumnWidthCellEditor extends EditingSupport {

    private final TableViewer tableViewer;

    public ColumnWidthCellEditor(final TableViewer tableViewer) {
        super(tableViewer);
        this.tableViewer = tableViewer;
    }

    @Override
    protected CellEditor getCellEditor(final Object element) {
        CellEditor cellEditor = new TextCellEditor(tableViewer.getTable());

        // Text with digits only
        ((Text) cellEditor.getControl()).addVerifyListener(new VerifyListener() {
            @Override
            public void verifyText(final VerifyEvent e) {
                e.doit = e.text.matches("[\\d]*");
            }
        });
        return cellEditor;
    }

    @Override
    protected boolean canEdit(final Object element) {
        return true;
    }

    @Override
    protected Object getValue(final Object element) {
        int columnWidth = ((ColumnModel) element).getColumnWidth();
        return Integer.toString(columnWidth);
    }

    @Override
    protected void setValue(final Object element, final Object value) {
        int columnWidth = Integer.valueOf((String) value);
        ((ColumnModel) element).setColumnWidth(columnWidth);
        tableViewer.update(element, null);
    }
}
